package LeetCode.leetcode56;

import java.util.HashMap;

class Solution {
    public int[][] merge(int[][] intervals) {
        HashMap<Integer, Integer> handleMerge = new HashMap<>();
        int size = intervals.length;
        boolean flag = false;
        for (int[] i : intervals) {
            int start = i[0];
            int end = i[1];
            if (!flag){
                flag = true;
                handleMerge.put(start, end);
                continue;
            }
            for (int j : handleMerge.keySet()) {
                int preS = j;
                int preE = handleMerge.get(j);
                if (start >= preS && end <= preE) {
                    //do nothing
                    handleMerge.put(start, end);
                }else if (start >= preS && end >= preE) {
                    handleMerge.remove(j);
                    int newStart = Math.min(start, preS);
                    int newEnd = Math.max(end, preE);
                    handleMerge.put(newStart, newEnd);
                    size--;
                }else if (start == preE) {
                    handleMerge.remove(j);
                    handleMerge.put(preS, end);
                    size--;
                }else if (start > preE) {
                    //do nothing
                    handleMerge.put(start, end);
                }
            }
        }
        int[][] ans = new  int[size][2];
        int j = 0;
        for (int i : handleMerge.keySet()) {
            ans[j][0] = i;
            ans[j][1] = handleMerge.get(i);
            j++;
        }
        return ans;
    }
}